var base_path = "http://music.tmradio.net/api/status.js?var=data&callback=tm_callback&";
var script_id = "tmradio_status";
var last_voted = 0;
var vote_blocked = false;

function send_vote(vote, track_id, no_block) {
    if (vote_blocked && !no_block) return false;
    if (!no_block) block_vote();
    track_id = track_id || tmr_current_status.id;
    if (track_id == last_voted) {
        alert("Вы уже проголосовали за эту песню!");
        return false;
        };
    console.log('Отправляем голос ' + vote + ' за трек ' + track_id);
    $.ajax({
        url: "/tmradio/vote/"+track_id+"/"+vote,
        success: function(data){
            last_voted = track_id;
            try {data = $.parseJSON(data)} 
            catch(e) { data = data }; // Э-(o_O)-Е
            if (data['status'] == undefined) {
                show_message('Какая-то ошибка... ('+data+')');
                if (!no_block) unblock_vote();
            } else {
                if (data['status'] == 'ok' && !no_block) setTimeout(force_tmr_status_update, 1000);
                if (data['message'] != undefined) show_message(data['message']);
                else show_message("Вроде отправлено...")
            };
        }
    });
};

function block_vote() {
    vote_blocked = true;
    $('#vote_rocks').addClass('blocked');
    $('#vote_sucks').addClass('blocked');
};

function unblock_vote() {
    vote_blocked = false;
    $('#vote_rocks').removeClass('blocked');
    $('#vote_sucks').removeClass('blocked');

}

function show_message(text, timeout) {
    function fade_message(text) { $('#vote_result').html(text); $('#vote_result').fadeIn('slow'); };
    function hide_message() { $('#vote_result').fadeOut('slow'); };
    fade_message(text); 
    setTimeout(hide_message, 3000);
};


function request_tm_token(aid_type) {
    $.ajax({
        url: "/tmradio/gettoken/"+aid_type,
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error: "+textStatus+"/"+errorThrown);
        },
        success: function(data){
            console.log(data['status']+" "+data['message']);
            if (data['status'] != undefined && data['status'] == 'ok') {
                show_message(data['message'], 10000);
            } else {
                show_message("Ошибка: "+data['message'], 10000);
            };
        }
    });
    return false;
};
